package com.pl.escape;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.apache.ibatis.mapping.BoundSql;

public class MapLikeSqlConverter extends AbstractLikeSqlConverter<Map> {
    public static final int TWO = 2;

    public void transferWrapper(String field, Map parameter) {
        AbstractWrapper wrapper = (AbstractWrapper) parameter.get(MYBATIS_PLUS_WRAPPER_KEY);
        parameter = wrapper.getParamNameValuePairs();
        String[] keys = field.split("\\.");

        String paramName = keys[2];
        String mapKey = String.format("%s.%s", new Object[]{"replaced.keyword", paramName});
        if (parameter.containsKey(mapKey) && Objects.equals(parameter.get(mapKey), Boolean.valueOf(true))) {
            return;
        }
        if (cascade(field)) {
            resolveCascadeObj(field, parameter);
        } else {
            Object param = parameter.get(paramName);
            if (hasEscapeChar(param)) {
                String paramStr = param.toString();
                parameter.put(keys[2], String.format("%%%s%%", new Object[]{escapeChar(paramStr.substring(1, paramStr.length() - 1))}));
            }
        }
        parameter.put(mapKey, Boolean.valueOf(true).toString());
    }


    public void transferSelf(String field, Map parameter) {
        if (cascade(field)) {
            resolveCascadeObj(field, parameter);
            return;
        }
        Object param = parameter.get(field);
        if (hasEscapeChar(param)) {
            String paramStr = param.toString();
            parameter.put(field, String.format("%%%s%%", new Object[]{escapeChar(paramStr.substring(1, paramStr.length() - 1))}));
        }
    }


    public void transferSplice(String field, Map parameter, BoundSql boundSql) {
        if (field.contains("__frch_item_")) {
            int index = field.indexOf(".");
            Map<String, Object> addtionalMap = new HashMap<>();
            String additionalKey = field.substring(0, index);
            addtionalMap.put(additionalKey, boundSql.getAdditionalParameter(additionalKey));
            resolveCascadeObj(field, addtionalMap);
            boundSql.setAdditionalParameter(additionalKey, addtionalMap.get(field));
            return;
        }
        if (cascade(field)) {
            resolveCascadeObj(field, parameter);
            return;
        }
        Object param = parameter.get(field);
        if (hasEscapeChar(param)) {
            parameter.put(field, escapeChar(param.toString()));
        }
    }


    private void resolveCascadeObj(String field, Map parameter) {
        /* 103 */
        int index = field.indexOf(".");
        /* 104 */
        Object param = parameter.get(field.substring(0, index));
        /* 105 */
        if (param == null) {
            return;
        }
        /* 108 */
        resolveObj(field.substring(index + 1), param);
    }

}


